import uaParserJs from 'ua-parser-js';
import devicePageMap from './config';
const uaParser = uaParserJs();

const {browser, cpu, device, engine, os, ua} = uaParser;

/**
 * 设备判断PC或者H5(包含ipad)
 */
const deviceType = ['mobile', 'tablet'].includes(device.type)
    ? 'mobile'
    : 'web';

/** 获取跳转url */
const getDevicePage = (options: {
    routeName: string; //           当前路由的名称, 需要和route的name对应上,匹配对应的配置
    params?: Object; //             路由的params内容
    queries?: Object; //            路由的queries内容
    mobile: string; //              要替换的路径上的H5项目的名称 eg:appac2
    web: string; //                 要替换的路径上的Pc项目的名称 eg:ac2
    curDevice: 'mobile' | 'web'; // 当前项目设备 mobile标示移动端项目,web标示pc端项目
}) => {
    let {routeName, params, queries, mobile, web, curDevice = 'web'} = options;
    // 没有名字的路由不做跳转检测
    if (!routeName) return;
    if (!!web && !!mobile) {
        // 没有对应跳转链接则不跳转
        const routeConfig = devicePageMap[routeName];
        if (!routeConfig) return;
        // 判断当前设备;
        if (deviceType !== curDevice) {
            // 标示项目和设备不同源
            if (routeConfig.supportDeviceSwitch) {
                let url = '';
                if (routeConfig.path) {
                    url = getFullUrl({url: routeConfig.path, params, queries});
                } else {
                    url = window.location.href;
                }
                const targetOrigan = curDevice === 'web' ? mobile : web;
                const currentOrigan = curDevice === 'web' ? web : mobile;
                url = url.replace(currentOrigan, targetOrigan);
                window.location.href = url;
            }
        }
    } else {
        throw new Error(`in ${!!web ? 'mobile' : 'web'} is not defined`);
    }
};

/** 获取url */
function getFullUrl({url = '', params = {}, queries = {}}) {
    // 没有url
    if (!url) return '';
    if (params) {
        const keys = Object.keys(params);
        for (let key of keys) {
            url = url.replace(new RegExp(`:${key}`), params[key]);
        }
    }
    if (queries) {
        const queryStr = objectConvertToQuery(queries);
        url += queryStr;
    }
    return url;
}

/** queries对象转string */
function objectConvertToQuery(payload: {
    [key: string]: string | number;
}): string {
    if (!payload) return '';
    let queryStr = '?';
    const keys = Object.keys(payload);
    const maxIndex = keys.length - 1;
    keys.forEach((key, index) => {
        queryStr += key + '=' + payload[key];
        if (index !== maxIndex) {
            queryStr += '&';
        }
    });
    return queryStr;
}

export {getDevicePage, deviceType, uaParser};
